package com.jeect.gateway4.util;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Set;

public class ResponseBody<T> implements Serializable {
	private static final long serialVersionUID = 6333797990288006658L;

	public Class<T> gettClass() {
		return tClass;
	}

	public void settClass(Class<T> tClass) {
		this.tClass = tClass;
	}

	private Class<T> tClass;
	public ResponseBody() {}
	public ResponseBody(Class<T> tClass) {
		this.tClass=tClass;
	}

	public ResponseBody(String code, String msg, T obj) {
		super();
		this.code = code;
		this.msg = msg;
		this.obj = obj;
	}

	
	public ResponseBody(ResponseCode response) {
		this.code=response.getCode();
		this.msg=response.getMsg();
	}
	public ResponseBody(ResponseCode response, T obj) {
		this.code=response.getCode();
		this.msg=response.getMsg();
		this.obj=obj;
	}


	private String code ="200";
	private String msg = "成功";
	
	private Object obj ;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {

		/*if(obj instanceof LinkedHashMap){
			LinkedHashMap map = (LinkedHashMap)obj;
			Set<String> set = map.keySet();
			for(String key :set){
				Class clazz = obj.getClass();

				Object value = map.get(key);
				try {
					Method method = clazz.getMethod("get" + key.substring(0, 1).toUpperCase() + key.substring(1), map.get(key).getClass());
					method.invoke(obj,value);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}*/
	/*	if(obj instanceof List){
			List result = new ArrayList();
			List<T> list = (List) obj;
			for(T t : list){
				t = onvert(t);
				result.add(t);
			}
			this.obj = result;
		}*/
		this.obj = obj;
	}

	public T getAndConvert(Class<T> tClass) throws Exception{
		T t = tClass.newInstance();
		if(obj instanceof LinkedHashMap){
			LinkedHashMap map = (LinkedHashMap)obj;
			Set<String> set = map.keySet();

			for(String key :set){
				/*Class clazz = obj.getClass();*/
				Object value = map.get(key);
				Class<?>  keytype  = value.getClass();

				if(keytype.getName().equals("java.lang.Double")|| keytype.getName().equals("java.lang.Float")){
					keytype = BigDecimal.class;
					value = new BigDecimal(value.toString());
				}
				try {

					Method method = tClass.getMethod("set" + key.substring(0, 1).toUpperCase() + key.substring(1),keytype);
					System.out.println(keytype.getName());
					method.invoke(t,value);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return t;
	}
}
